<?php
namespace app\common\model;
use think\Validate;
use think\Db;

class OrdersItem extends Base
{
	public static $progress_desc = [
		'0'	=> '已取消',
		'1'	=> '新订单',
		'10'=> '待重报单',
		'2'	=> '已报单',
		'3'	=> '已到货',
		'4'	=> '已发货',
		'5'	=> '退货',
		'6'	=> '换货'
	];
	public static $dangkou = ['金宝','金都','金像','金美','汇美','2号楼','桃花江','万通','UUS','山东','上海','东莞','浙江','深圳','国大','广大','凰岗','老申泽','成大','白云','嘉星','其它'];
	public function orderInfo()
	{
		return $this->belongsTo('Orders','order_id');
	}
	public function goodsInfo()
	{
		return $this->belongsTo('Goods','goods_id');
	}
	public function stockInItems()
	{
		return $this->hasMany('StockIn','order_item_id');
	}
	public function purchaseItems()
	{
		return $this->hasMany('Purchase','order_item_id');
	}
	public function expItems()
	{
		return $this->hasMany('ExpressItem','order_item_id');
	}
	public function insert($rows, $order_id)
	{
        foreach ($rows as $key => $row) {
        	$row['order_id'] = $order_id;
        	$row['order_sn'] = $key + 1;
        	
        	$res = $this->add($row, true);
        	if ($res['code']==0) {
        		return $res;
        	}
        }

        return [
    		'code'	=> 1,
    		'msg'	=> '成功'
    	];
	}
	public function updateProgress($id)
	{
		$qty = $this->where('id', $id)->value('qty');
		//报单信息
		$purchase = Db::name('purchase')->where(['order_item_id'=>$id,'status'=>1])->find();
		//到货信息
		$stock_in_qty = Db::name('stock_in')->where(['order_item_id'=>$id,'status'=>1])->sum('qty');
		//发货信息
		$exp_qty = Db::name('express_item')->where('order_item_id', $id)->sum('qty');
		if ($purchase) {
			$this->where('id', $id)->update(['progress'=>2]);
		} elseif ($exp_qty >= $qty) {	//已发货
			$this->where('id', $id)->update(['progress'=>4]);
		} elseif ($stock_in_qty) {	//未发
			$this->where('id', $id)->update(['progress'=>3]);
		} 
	}
}